package 力扣_算法题综合.高频面试算法;

import java.util.ArrayList;
import java.util.List;

public class 螺旋矩阵_54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        int row = matrix.length, col = matrix[0].length;
        int left = 0, right = col - 1, up = 0, down = row - 1;
        int count = 0, total = row * col;
        List<Integer> res = new ArrayList<>();
        while(count < total){
            for(int i = left;i <= right && count < total;i++){
                res.add(matrix[up][i]);
                count++;
            }
            up++;
            for(int i = up;i <= down && count < total;i++){
                res.add(matrix[i][right]);
                count++;
            }
            right--;
            for(int i = right; i >= left && count < total;i--){
                res.add(matrix[down][i]);
                count++;
            }
            down--;
            for(int i = down;down >= up && count < total;i--){
                res.add(matrix[i][left]);
                count++;
            }
            left++;
        }
        return res;
    }

    public List<Integer> spiralOrder2(int[][] matrix) {
        int row = matrix.length, col = matrix[0].length;
        int left = 0, right = col - 1, up = 0, down = row - 1;
        int count = 0, total = row * col;
        List<Integer> res = new ArrayList<>();
        while(count < total){
            for(int i = left;i <= right && count < total;i++){
                res.add(matrix[up][i]);
                count++;
            }
            up++;
            for(int i = up;i <= down && count < total;i++){
                res.add(matrix[i][right]);
                count++;
            }
            right--;
            for(int i = right;i >= left && count < total;i--){
                res.add(matrix[down][i]);
                count++;
            }
            down--;
            for(int i = down;i >= up && count < total;i--){
                res.add(matrix[i][left]);
                count++;
            }
            left++;
        }
        return res;
    }
}
